'use strict';
const BaseService = require('./base');
const ResponseUtil = require('../utils/ResponseUtil');
const StringUtil = require('../utils/StringUtil');
const HelperUtil = require('../utils/HelperUtil');
const RCEM = require('../utils/ResultCodeEnumMsg');
const VRCE = require('../utils/ViewResultCodeEnum');
const Constant = require('../config/Constant');

class ComplaintService extends BaseService {


    async getComplaintList({keyword, orderId, pageNum, pageSize, status}) {
        let loginUserInfo = this.ctx.getLoginInfo();
        let operatorType = loginUserInfo.operatorType;
        let operatorId = loginUserInfo.operatorId;
        let createBy = loginUserInfo.createBy;
        let tenantId = loginUserInfo.tenantId;

        let sql = 'select SQL_CALC_FOUND_ROWS * from t_complaint where tenant_id=? ';


        let wheres = [
            {column: 'status', value: status}
        ];

        let formatSqlResult = this.formatSqlWhere(sql, wheres);

        sql = formatSqlResult[0];

        let options = formatSqlResult[1];

        if (keyword) {
            sql += ` AND (order_id like "%"?"%" or product_name like "%"?"%" ) `;
            options.push(keyword);
            options.push(keyword);
        }

        sql += " order by create_time desc ";
        sql = this.addMysqlPageSize(sql, pageNum, pageSize);
        let result = await this.queryPageData(sql, [tenantId].concat(formatSqlResult[1]));

        return result;
    }

    async selectComplaintById(productId){
        let sql = 'select * from t_complaint where id=? ';
        let result = await this.executeSqlFirst(sql,[productId]);
        return result;
    }

    async processComplaint() {
        let loginUserInfo = this.ctx.getLoginInfo();
        let operatorType = loginUserInfo.operatorType;
        let operatorId = loginUserInfo.operatorId;
        let createBy = loginUserInfo.createBy;
        let tenantId = loginUserInfo.tenantId;

        let {id, operResult,status} = this.ctx.request.body;
        if (!id || !operResult) {
            return ResponseUtil.resError('参数错误');
        }

        const complaint = await this.selectComplaintById(id);
        if(!complaint){
            return ResponseUtil.resError('未找到投诉');
        }

        if(complaint.tenantId != tenantId){
            return ResponseUtil.resError(RCEM.NO_PERMISSION[1], RCEM.NO_PERMISSION[0]);
        }

        if(complaint.status != 0){
            return ResponseUtil.resError('投诉已处理');
        }

        let sql = 'update t_complaint set oper_by=?,oper_by_id=?,oper_result=?,oper_time=?,status=? where id=?';
        return await this.executeSqlSucc(sql, [createBy, operatorId, operResult,new Date(),status,id])
    }


}

module.exports = ComplaintService;
